const baseURL = 'https://fxg.jinritemai.com/'
const getApiUrl = {
  getCoupon: 'marketing/coupons/v1/list',
  getcouponsD: 'marketing/coupons/v1/shopcoupons/'
}
const ECCOMMARKETSHOP = "ecom_market_shop"

onmessage = function (e) {//监听主进程的消息
  switch (e.data.type) {
    case 'getCoupon':
      getCouponList(e.data.data)
      break;
    default:
      break;
  }
}
let getCouponListData = []
let proterData = []
let inter = 1
let addgetAllWei = []
const manjianActivityData = []
function getCouponList(data, isket = false) {
  return new Promise((resolve, reject) => {
    const upData = {
      coupon_type_group: data.coupon_type_group || 1, // 优惠券类型==》 0：全部 1：通用优惠券 2：涨粉券 3：达人专属 4：店铺新人
      favoured_type: data.favoured_type || 0, //优惠方式==》 0：全部 21：全店通用-折扣 22：全店通用-立减 23：全店通用-满减 41：指定商品-折扣 42：指定商品-立减 43：指定商品-满减
      status: data.status || 3, // 优惠券状态==》0：全部 2：已作废 3：生效中 4：过期
      page: data.page || 1,
      size: data.pageSize || data.page_size || data.size || 100,
      sort_by_stock: data.sort_by_stock || false, // 排序开关无用
      _bid: data._bid || ECCOMMARKETSHOP
    }
    const url = baseURL + getApiUrl.getCoupon + splitJoint(upData)
    fetchWithTimeout(url, { timeout: 4000 }).then(response => {
      if (response.ok) {
        response.json().then(data => {

          getCouponListData.push(...data.data.filter((item) => {
            if (item.goods_count == 1) {
              // console.log('当个品的优惠券', item)
              const contercomter = {
                couponData: item,
                product_id: item.url.split('?id=')[1],
                channel_id: '',
                channel_type: 0,
                img: '',
                is_combined: false,
                is_package_product: 0,
                max_price: 0,
                min_price: 0,
                name: '',
                price: 0
              }
              manjianActivityData.push(contercomter)
              return false
            }
            return item.coupon_source !== 6
          }).map(item => {
            // console.log('请求的结果数据...', item)
            return { coupon_meta_id: item.coupon_meta_id }
          }))
          // console.log('请求的结果数据...', getCouponListData)
          // console.log('请求的结果数据', data.total)
          if (data.total > (upData.page * upData.size) && !isket) {
            do {
              inter++
              proterData.push(Object.assign(JSON.parse(JSON.stringify(upData)), { page: inter }))
            } while (data?.total > (inter * upData.size))
            getDateaAllData()
            return
          }
          if (!isket && data.total <= (upData.page * upData.size)) {
            getDateaAllData()
            return
          }
          isket && resolve(getCouponListData)
        })
        return
      }
    }).catch(err => {
      // 错误重新发起请求
      getCouponList(data, true).then(res => {
        // console.log('失败重新的请求结果00', res)
        resolve(res)
      })
    })
  })
}

function getDateaAllData() {
  const getAliter = proterData.map(item => {
    // console.log('item', item)
    return getCouponList(item, true)
  })
  Promise.all(getAliter).then(res => {
    // console.log('请求的结果数据ALL', getCouponListData)

    getDetellAll(getCouponListData)
    function getDetellAll(datas) {
      getCouponListData = null
      const aplitData = datas.splice(0, 500)
      // console.log('work内 优惠券情况', aplitData)

      if (aplitData && aplitData.length) {
        const getAllMteru = aplitData.map(alliten => {
          return getCouponDetails({ coupon_meta_id: alliten.coupon_meta_id })
        })
        Promise.all(getAllMteru).then(res => {
          // console.log('res', res)
          // if(!res) debugger
          addgetAllWei.push(...res)
          getDetellAll(datas)
        }).catch(err => {
          // console.log('请求的错误信息001144', err)
          // getDetellAll(datas)
        })
      } else {


        addgetAllWei.forEach(acdt => {
          // console.log('console.****', acdt)
          if (acdt) {
            if (!acdt?.goods || !acdt?.goods.length) {
              // console.log('acdt可能全店++++++++++++++++++++++++++++++', acdt)
              // 全店通用的优惠券
              const addallgoodsdata = {
                isallgoods: true, // 是否全店通用
                couponData: acdt
              }
              manjianActivityData.push(addallgoodsdata)
            }
            acdt?.goods && acdt?.goods.length && acdt?.goods.forEach(aply => {
              aply.couponData = {}
              for (let key in acdt) {
                if (key !== 'goods') {
                  aply.couponData[key] = acdt[key]
                }
              }
              // console.log('aply++--*', aply)
              manjianActivityData.push(aply)
            })
          }

        })
        postMessage({
          type: 'putCoupon',
          data: manjianActivityData
        })
      }
    }
  })
}


function getCouponDetails(data) {
  return new Promise((resolve, reject) => {
    // console.log('sa', sa)
    // if(resolveAs) console.log('sasa', data)
    // data.resolve = data.resolve || resolve
    fetchWithTimeout(`${baseURL}${getApiUrl.getcouponsD}${data.coupon_meta_id}?_bid=ecom_market_shop`, { timeout: 3000 }).then(response => {
      if (response.ok) {
        response.json().then(dataa => {
          //resolveAs ? resolveAs(dataa.data) : 
          resolve(dataa.data)
        })
        return
      }
      reject(new Error('Network response was not ok.'))
    }).catch(err => {
      // 错误重新发起请求
      // console.log('请求错误', err)
      // debugger
      getCouponDetails(data).then(res => {
        // console.log('失败的重新请求', res)
        // debugger
        // console.log('dede', res)
        // resolve(res)
        resolve(res)
        // data.resolve(res)
      })
    })
  })
}

const fetchWithTimeout = (resource, options = {}) => {
  const { timeout = 8000 } = options; // 设置默认超时时间为8000ms

  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);

  const response = fetch(resource, {
    ...options,
    signal: controller.signal
  }).then((response) => {
    clearTimeout(id);
    return response;
  }).catch((error) => {
    clearTimeout(id);
    throw error;
  });

  return response;
}

function splitJoint(obj) {
  let arr = []
  for (let key in obj) {
    arr.push(key + "=" + obj[key])
  }
  return arr.length > 0 ? "?" + arr.join("&") : ""
}